package com.example.listview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.example.listview.adpater.FruitAdapter;
import com.example.listview.entity.Fruit;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    private Context context = MainActivity.this;

    private String[] data = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"};

    ArrayList<Fruit> fruitList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        /**
         * 方式一：
         *
         * R.layout.support_simple_spinner_dropdown_item为Android自带的布局，可以直接使用。也可以自定义list_view对象，如下所示：
         */
//        ArrayAdapter<String> adapter = new ArrayAdapter<>(context, R.layout.support_simple_spinner_dropdown_item, data);
//        ListView  listView = findViewById(R.id.list_view);
//        listView.setAdapter(adapter);

        /**
         * 方式二：自定义布局
         */
        initFruits(); // 初始化水果数据
        FruitAdapter fruitAdapter = new FruitAdapter(context, R.layout.fruit_item, fruitList);
        ListView listView = findViewById(R.id.list_view);
        listView.setAdapter(fruitAdapter);

        //设置 ListView 点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Fruit fruit = fruitList.get(position);
                Toast.makeText(context, fruit.getName(), Toast.LENGTH_SHORT).show();
            }
        });

    }

    private void initFruits() {
        Fruit apple = new Fruit("Apple", R.drawable.apple);
        Fruit origin = new Fruit("origin", R.drawable.origin);
        Fruit banana = new Fruit("banana", R.drawable.banana);
        for (int i = 0; i < 10; i++) {
            fruitList.add(apple);
            fruitList.add(origin);
            fruitList.add(banana);


        }

    }
}